package com.product_customer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {
    public static void main(String[] args) {
        Data2 data2 = new Data2();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data2.methodadd();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data2.methodreduce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data2.methodreduce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data2.methodadd();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();

    }
}

//判断等待，业务，通知
class Data2{//数字、资源,只要是并发编程就一定要加锁

    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    /*
    condition.await(); //等待
    condition.signalAll();//唤醒全部
    */

    //method +1  -1
    public void methodadd() throws InterruptedException {
        lock.lock();
        try {
            while (number!=0){
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            condition.signalAll();
            lock.unlock();
        }

    }

    public void methodreduce() throws InterruptedException {
        lock.lock();
        try {
            while (number==0){
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            //通知其他线程，-1完毕
            condition.signalAll();
            lock.unlock();
        }

    }
}
